const express = require('express');
const router = express.Router();
const wordList = require('./data');

/*
@description: get a word from word list and return it to app
@return: an Object in json text
@param: startWith--OPTIONAL
            select a word's first letter
*/
router.get('/getWord', (req, res) => {
    // get URL query param
    const initial = req.query.startWith;
    const listLength = wordList.length;
    console.log(`get param: startWith: ${initial}`);
    // generate the initial word
    let chosenWord = randomWord(listLength);
    if (initial != undefined) {
        let loopCounter = 0;
        do {
            chosenWord = randomWord(listLength);
            loopCounter++;
        } while (chosenWord.charAt(0) != initial && loopCounter <= 1000);
        // limit for 1000 times, avoiding infinite loop
    }
    // description in README
    res.json({
        timeStamp: Date.now(),
        startWith: initial,
        result: {
            word: chosenWord,
            wordArr: Array.from(chosenWord)
        },
    });
    console.log(`return with: ${chosenWord}`);
    console.log(`==========================`);
});


/*
@description: check a word's validity, return the result
@return: bool in json text
@param: word--ESSENTIAL
            the word to check
*/
router.get('/checkExist', (req, res) => {
    const toCheck = req.query.word;
    console.log(`checking word: ${toCheck}`);
    let index = wordList.indexOf(toCheck);
    let exist = false;
    if( index === -1 ) {
        exist = false;
    } else {
        exist = true;
    }
    console.log(`check result: ${exist}`);
    console.log(`==========================`);
    res.json({
        timeStamp: Date.now(),
        checkWord: toCheck,
        result: {
            exist: exist
        },
    });
});

function randomWord(listLength) {
    let index = Math.floor(Math.random() * listLength);
    return wordList[index];
}

module.exports = router;
